const express = require('express');
const path = require('path');
const cors = require('cors');
const tokenSer = require('../util/token');
const PROT = 3000;
const app = express();

// 跨域
app.use(cors())

const staticRoot = path.resolve(__dirname, "../public");
app.use(express.static(staticRoot, {
    dotfiles: 'allow', //设置可以访问.文件
}))

//验证token
app.all('*', async(req, res, next) => {
        if (req.path == '/api/user/login') return next()
        if (req.path == '/api/user/register') return next()
        let token = req.headers.authorization;
        if (!token) return res.send({
            data: {},
            meta: { msg: 'token为空', status: 403 }
        })
        let result = await tokenSer.en(token);
        return result.flag ? next() : res.send({
            data: {},
            meta: { msg: result.msg, status: 403 }
        })
    })
    //解析 URL-encoded 格式的请求体数据
app.use(express.urlencoded({ extended: false }));
//解析表单中的 JSON 格式的数据
app.use(express.json());

//用户
app.use('/api/user',require('./api/user.js'));

//商品
app.use('/api/goods',require('./api/goods'));

// 杂志
app.use('/api/magazine', require('./api/magazine'));
// 商家
// app.use('/api/business',require('./api/business'));

//反馈
app.use('/api/feedback',require('./api/feedback'));
app.use('/api/business', require('./api/business'));

// 上传接口
app.use('/api/upload', require('./api/upload'));

// 用户评论
app.use("/api/comment", require('./api/comment'));

app.use((err, req, res, next) => {
    if (err) {
        console.log('错误')
        res.send({
            meta: {
                status: '未知错误',
                status: 500
            }
        })
    }
})

app.listen(PROT, () => {
    console.log('服务开启', PROT)
})